package com.heima.schedule.service.Impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.hbase.thirdparty.io.netty.util.internal.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Set;

import static com.heima.common.constants.ScheduleConstants.*;

@Service
@Transactional
@Slf4j
public class TaskServiceImpl implements TaskService {
    @Resource
    private TaskinfoMapper taskinfoMapper;
    @Resource
    private TaskinfoLogsMapper taskinfoLogsMapper;
    @Resource
    private CacheService cacheService;

    @Override
    public long addTask(Task task) {

        boolean isAddTaskToDB = AddTaskToDB(task);

        if (isAddTaskToDB) {

            AddTaskToCache(task);
        }


        return task.getTaskId();
    }


    private void AddTaskToCache(Task task) {


        try {
            long futureTimestamp = Instant.now().plus(5, ChronoUnit.MINUTES).toEpochMilli();
            String key = task.getTaskType() + "_" + task.getPriority();
            long nowTimestamp = Instant.now().toEpochMilli();
            long executeTimestamp = task.getExecuteTime();
            if (executeTimestamp <= nowTimestamp) {
                cacheService.lLeftPush(TOPIC + key, JSON.toJSONString(task));
            } else if (executeTimestamp <= futureTimestamp) {
                cacheService.zAdd(FUTURE + key, JSON.toJSONString(task), task.getExecuteTime());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean AddTaskToDB(Task task) {

        boolean flag = false;
        try {
            Taskinfo taskinfo = new Taskinfo();

            BeanUtils.copyProperties(task, taskinfo);
            taskinfo.setExecuteTime(LocalDateTime.ofInstant(Instant.ofEpochMilli(task.getExecuteTime()), ZoneId.systemDefault()));
            taskinfoMapper.insert(taskinfo);
            task.setTaskId(taskinfo.getTaskId());
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo, taskinfoLogs);
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(SCHEDULED);
            taskinfoLogsMapper.insert(taskinfoLogs);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }


    @Override
    public boolean cancelTask(long taskId) {

        boolean flag = false;
        Task task = updateDB(taskId, CANCELLED);
        if (task != null) {

            removeTaskFromCache(task);
            flag = true;
        }
        return flag;
    }

    @Override
    public Task poll(int type, int priority) {
        Task task = null;
        try {
            String key = TOPIC + type + "_" + priority;
            String TaskJson = cacheService.lLeftPop(key);
            if (!StringUtil.isNullOrEmpty(TaskJson)) {
                task = JSON.parseObject(TaskJson, Task.class);
                updateDB(task.getTaskId(), EXECUTED);
            }
        } catch (Exception e) {
            log.error("poll task exception");
        }

        return task;
    }

    /**
     * 数据刷新方法，使用 Cron 定时触发。
     * 每分钟的第0秒触发一次。
     */
    @Scheduled(cron = "0 * * * * *")
    public void refresh() {
        // 尝试获取一个断时间为10秒的Redis锁，防止并发执行
        boolean lock = cacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 10);

        if (lock) {
            // 扫描所有满足 FUTURE* 规则的缓存键
            Set<String> FutureKey = cacheService.scan(FUTURE + "*");

            for (String futureKey : FutureKey) {
                // 获取该缓存键的所有任务，任务的执行时间范围之内的现在
                Set<String> tasks = cacheService.zRange(futureKey, 0, Instant.now().toEpochMilli());
                String topicKey = TOPIC + futureKey.split("_")[1];

                // 如果任务的集合不为空，则执行缓存更新
                if (CollectionUtils.isNotEmpty(tasks)) {
                    cacheService.refreshWithPipeline(futureKey, topicKey, tasks);
                    System.out.println(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-ddHH:mm:ss")) + ":" + futureKey);
                }
            }
        }
    }

    @Scheduled(cron = "0 */5 * * * ?")
    public void reloadCache() {
        creatCache();
        List<Taskinfo> taskinfos = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().lt(Taskinfo::getExecuteTime, LocalDateTime.now()));

        if (CollectionUtils.isNotEmpty(taskinfos)) {
            for (Taskinfo taskinfo : taskinfos) {
                System.out.println(taskinfo);
                Task task = new Task();
                BeanUtils.copyProperties(taskinfo, task);
                task.setExecuteTime(taskinfo.getExecuteTime().toInstant(ZoneOffset.ofHours(8)).toEpochMilli());
                AddTaskToCache(task);
            }
        }
        int i = 0;
        i++;
        log.info("数据库同步到缓存成功:" + i);


    }

    private void creatCache() {
        Set<String> topicKeys = cacheService.scan(TOPIC + "*");
        Set<String> futureKeys = cacheService.scan(FUTURE + "*");
        cacheService.delete(topicKeys);
        cacheService.delete(futureKeys);
    }


    private void removeTaskFromCache(Task task) {

        long executeTime = task.getExecuteTime();
        long now = LocalDateTime.now().atZone(ZoneOffset.systemDefault()).toInstant().toEpochMilli();
        String key = task.getTaskType() + "_" + task.getPriority();
        if (executeTime <= now) {
            cacheService.lRemove(TOPIC + key, 0, JSON.toJSONString(task));
        } else {
            cacheService.zRemove(FUTURE + key, JSON.toJSONString(task));
        }
    }

    private Task updateDB(long taskId, int status) {
        Task task = null;
        try {
            taskinfoMapper.deleteById(taskId);

            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
            taskinfoLogs.setStatus(status);
            taskinfoLogsMapper.updateById(taskinfoLogs);

            task = new Task();
            BeanUtils.copyProperties(taskinfoLogs, task);

            task.setExecuteTime(taskinfoLogs.getExecuteTime().toInstant(ZoneOffset.ofHours(8)).toEpochMilli());
        } catch (Exception e) {
            log.error("task cancel exception taskId={}", taskId);
        }
        return task;
    }


}
